package com.example.blog.component;

import org.springframework.stereotype.Component;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * @Question DrawCheckCode
 * @Date 2023/1/12 15:02
 * @Solution
 */
@Component
public class DrawCheckCode {
    private String checkCode;
    public String getCheckCode() {
        return checkCode;
    }
    public String getNum() {
        int ran=(int)(Math.random()*9000)+1000;
        return String.valueOf(ran);
    }
    public Color getColor() {
        Random random = new Random();
        //获取rgb参数
        int r=random.nextInt(256);
        int g=random.nextInt(256);
        int b=random.nextInt(256);
        return new Color(r,g,b);
    }
    public BufferedImage doDraw() {
        //设置图片参数
        BufferedImage image = new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);
        //画笔
        Graphics graphics = image.getGraphics();
        //画长方形
        graphics.fillRect(0,0,80,30);
        //绘制50条干扰条
        for(int i=0;i<50;i++) {
            Random random = new Random();
            int xBegin=random.nextInt(80);
            int yBegin=random.nextInt(30);
            int xEnd=random.nextInt(xBegin+10);
            int yEnd=random.nextInt(yBegin+10);
            //画笔颜色随机
            graphics.setColor(getColor());
            //绘制线条
            graphics.drawLine(xBegin,yBegin,xEnd,yEnd);
        }
        //绘制验证码
        //设置字体
        graphics.setFont(new Font("seif",Font.BOLD,18));
        //画笔颜色
        graphics.setColor(getColor());
        //得到随机数字
        String cheCode=getNum();
        checkCode=cheCode;
        //在验证码字符间加上空格
        StringBuffer buffer = new StringBuffer();
        for(int i=0;i<cheCode.length();i++){
            buffer.append(cheCode.charAt(i)+" ");
        }
        //绘制验证码
        graphics.drawString(buffer.toString(),15,20);
        return image;
    }
}
